﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.BarCode
{
    class UPCSupplement2
    {
        private string[] EAN_CodeA = { "0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011" };
        private string[] EAN_CodeB = { "0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111" };
        private string[] UPC_SUPP_2 = { "aa", "ab", "ba", "bb" };


        private static volatile UPCSupplement2 instance;

        private static object syncRoot = new Object();

        public static UPCSupplement2 Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new UPCSupplement2();
                        }
                    }
                }
                return instance;
            }
        }

        public string GetBarCode(string barcode)
        {
            if (barcode.Length != 2) throw new Exception("EUPC-SUP2-1: Invalid data length. (Length = 2 required)");

            if (!Pixysoft.NumberCoder.Instance.IsInt64(barcode))
                throw new Exception("EUPC-SUP2-2: Numeric Data Only");

            string pattern = "";

            try
            {
                pattern = this.UPC_SUPP_2[Int32.Parse(barcode.Trim()) % 4];
            }//try
            catch { throw new Exception("EUPC-SUP2-3: Invalid Data. (Numeric only)"); }

            string result = "1011";

            int pos = 0;
            foreach (char c in pattern)
            {
                if (c == 'a')
                {
                    //encode using odd parity
                    result += EAN_CodeA[Int32.Parse(barcode[pos].ToString())];
                }//if
                else if (c == 'b')
                {
                    //encode using even parity
                    result += EAN_CodeB[Int32.Parse(barcode[pos].ToString())];
                }//else if

                if (pos++ == 0) result += "01"; //Inter-character separator
            }//foreach
            return result;
        }
    }
}
